//
//  BuddyListViewController.swift
//  SwiftIM
//
//  Created by WuZhijian on 14/12/6.
//  Copyright (c) 2014年 com.liveln. im. All rights reserved.
//

import UIKit

class BuddyListViewController: UITableViewController,statusDL,MessageDL,UIAlertViewDelegate{
    
    @IBOutlet weak var myStatus: UIBarButtonItem!
    //未读消息
    var unreadList = [WXMessage]()
    //登陆状态
    var logined = false
    
    //好友状态
    var ztlist = [status]()
    
    //当前选择聊天的好友昵称
    var currentBuddyName = ""
    
    func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){
        self.performSegueWithIdentifier("toLoginSeque", sender: self)
    }
    //切换用户登陆状态
    @IBAction func log(sender: UIBarButtonItem) {
        //根据当前状态调整
        if logined
        {
            logout()
            
            //更改状态
            //sender.image = UIImage(named: "off")
        }
        else
        {
            login()
            
            //更改状态
            //sender.image = UIImage(named: "on")
        }
        
    }
    
    //总代理
    func zdl() -> AppDelegate {
        return UIApplication.sharedApplication().delegate as AppDelegate
    }
    
    //自己离线
    func meOff() {
        self.logout()
    }
    
    //上线
    func isOn(zt:status) {
        //查找状态列表
        for (index,oldzt) in enumerate(ztlist)
        {
            //如果找到旧用户状态
            if(zt.name == oldzt.name)
            {
                //移除状态
                ztlist.removeAtIndex(index)
                //退出循环
                break
                
            }
        }
        
        ztlist.append(zt)
        //刷新列表
        self.tableView.reloadData()
    }
    
    //下线
    func isOff(zt: status) {
        //查找状态列表
        for (index,oldzt) in enumerate(ztlist)
        {
            //如果找到旧用户状态
            if(zt.name == oldzt.name)
            {
                //更新状态
                ztlist[index].isOnLine = false
                //退出循环
                break
                
            }
        }
        
        //刷新列表
        self.tableView.reloadData()

    }
    
    //收到离线或未读消息
    func newMessage(msg: WXMessage) {
        
        //判断消息是否为空
        if (msg.body != "")
        {
            unreadList.append(msg)
            //刷新表格
            self.tableView.reloadData()
        }
    }
    
    //登陆
    func login(){
        
        //清空数组
        unreadList.removeAll(keepCapacity: false)
        ztlist.removeAll(keepCapacity: false)
        
        let myId = NSUserDefaults.standardUserDefaults().stringForKey("weixinID")

        if(myId == "@im.livelu.cn")
        {
            var show = UIAlertView()
            
            show.title = "提示信息"
            show.message = "请输入用户名"
            show.addButtonWithTitle("确定")
            show.delegate = self
            show.show()
        }
        
        zdl().connect()
        //导航左边状态
        //myStatus.image = UIImage(named: "on")
        myStatus.title = "在线"
        logined = true
        //更新标题
        self.navigationItem.title = "好友列表"
        
        //通知表格更新数据
        self.tableView.reloadData()
    }
    
    //退出
    func logout(){
        //清空数组
        unreadList.removeAll(keepCapacity: false)
        ztlist.removeAll(keepCapacity: false)
        
        zdl().closeConnect()
        
        //导航左边状态
        //myStatus.image = UIImage(named: "off")
        myStatus.title = "离线"
        
        logined = false
        
        //更新标题
        let myId = NSUserDefaults.standardUserDefaults().stringForKey("weixinID")
        self.navigationItem.title = "好友列表"
        
        //通知表格更新数据
        self.tableView.reloadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //获取用户名
        let myId = NSUserDefaults.standardUserDefaults().stringForKey("weixinID")
        
        //自动登陆
        if(logined == false)
        {
           self.login()
        }
//        else
//        {
//           self.login()
//        }
        
        //接管状态代理
        zdl().ztdl = self

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }
    
    override func viewDidAppear(animated: Bool) {
        //接管消息代理
        zdl().xxdl = self
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    //表格有几个数组
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    //表格行数
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return ztlist.count
    }
    
    //设置单元格数据
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("buddyListCell", forIndexPath: indexPath) as UITableViewCell

        // Configure the cell...
        //好友名字
        let name = ztlist[indexPath.row].name
        
        //好友状态
        let online = ztlist[indexPath.row].isOnLine
        if(online)
        {
            cell.imageView?.image = UIImage(named: "on")
        }
        else
        {
            cell.imageView?.image = UIImage(named: "off")
        }
        
        //未读消息条数
        var unReadNumber = 0
        for msg in unreadList
        {
            if(msg.from == name)
            {
                unReadNumber++
            }
        }
        
        cell.textLabel?.text = name + "（\(unReadNumber)）"
        
        return cell
    }
    
    //选择好友
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        //保存好友昵称
        self.currentBuddyName = ztlist[indexPath.row].name
        
        //跳转到聊天窗口
        self.performSegueWithIdentifier("toChatSeque", sender: self)
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        //判断是否跳转到聊天界面
        if(segue.identifier == "toChatSeque")
        {
            //获取聊天试图控制器
            let dest = segue.destinationViewController as ChatViewController
            
            //把当前选中单元格的数据传递给聊天试图
            dest.toBuddyName = self.currentBuddyName
            
            //传递未读消息到聊天试图
            for msg in unreadList
            {
                if(msg.from == self.currentBuddyName)
                {
                    dest.msgList.append(msg)
                }
            }
            
            //把相应的未读消息，从未读消息手动移除
            removeValueFromArray(self.currentBuddyName, &unreadList)
            
            //刷新表格
            self.tableView.reloadData()
            
            
        }
    }
    

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */
    @IBAction func unwindToBList(segue: UIStoryboardSegue) {
        //如果登陆界面完成按钮点击
        let source = segue.sourceViewController as LoginViewController
        
        if source.requireLogin
        {
            //注销上个用户
            self.logout()
            
            //登陆现有用户
            self.login()
        }
    }

}
